package com.horizon.common.configuration;

import com.horizon.common.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.core.env.Environment;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 静态资源配置
 *
 * @author wangfuwei
 * @version 2018-08-09
 */
@SpringBootConfiguration
public class StaticResourceConfiguration implements WebMvcConfigurer {

    /**
     * 自定义templates下的静态文件夹
     */
    private final String STATIC_PREFIX = "/static/";

    @Autowired
    private Environment environment;

    /**
     * 动态注册静态资源文件夹
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //静态资源拦截前缀
        String staticPath = environment.getProperty("spring.mvc.static-path-pattern", String.class, "/**");

        //动态解析templates下所有的文件夹，获取所有 STATIC_PREFIX 文件夹
        Set<String> staticSet = new HashSet<>();
        staticSet.add("classpath:/static/");
        ClassLoader cl = ClassUtils.getDefaultClassLoader();
        String classPath = (cl != null ? cl.getResource("") : ClassLoader.getSystemResource("")).getPath();
        List<File> fileList = FileUtil.getAllFile(classPath + "templates");
        for (File file : fileList) {
            String filePath = file.getPath().replace(classPath, "classpath:/");
            if (filePath.contains(STATIC_PREFIX)) {
                filePath = filePath.substring(0, filePath.indexOf(STATIC_PREFIX));
                staticSet.add(filePath + STATIC_PREFIX);
            }
        }

        //动态添加静态 STATIC_PREFIX 文件夹
        ResourceHandlerRegistration resourceHandlerRegistration = registry.addResourceHandler(staticPath);
        Iterator<String> iterator = staticSet.iterator();
        while (iterator.hasNext()) {
            resourceHandlerRegistration.addResourceLocations(iterator.next());
        }
    }
}
